package cn.com.gdut.ppj.comtroller;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.gdut.ppj.common.service.ICommonService;
import cn.com.gdut.ppj.common.utils.UUIDFactory;
import cn.com.gdut.ppj.hr.service.IHrService;
import cn.com.gdut.ppj.model.TbCandidateRecruitmentInfo;
import cn.com.gdut.ppj.model.TbCompany;
import cn.com.gdut.ppj.model.TbHr;
import cn.com.gdut.ppj.model.TbProjectExperience;
import cn.com.gdut.ppj.model.TbRecruitmentInformation;
import cn.com.gdut.ppj.model.TbResume;
import cn.com.gdut.ppj.model.TbSchoolStudyInfo;
import cn.com.gdut.ppj.model.TbUser;
import cn.com.gdut.ppj.model.TbUserResumeRef;
import cn.com.gdut.ppj.model.TbWorkExperience;
import cn.com.gdut.ppj.user.service.IUserService;

@Controller
@RequestMapping(value="/user")
public class UserController {
	
	@Resource
	private IUserService userService;
	@Resource
	private IHrService hrService;
	@Resource
	private ICommonService commonService;
	
	@RequestMapping(value="/getRecruitmentInformationsPage",method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView getRecruitmentInformationsPage(HttpSession session,
			String salaryMin,
			String edu,
			String workCity,
			String positionDesc,
			Integer num
			){
		ModelAndView mav = new ModelAndView();
		TbUser user = (TbUser) session.getAttribute("user");
		
		Map<String, String> hash = new HashMap<>();
		if(null != salaryMin && ""!=salaryMin){
			hash.put("salaryMin", salaryMin.trim());
//			tri.setSalaryMin(salaryMin.trim());
		}
		if(null != edu && ""!=edu){
//			tri.setEducationalBackgroundDesc("%"+edu.trim()+"%");
			hash.put("educationalBackgroundDesc", "%"+edu.trim()+"%");
		}
		if(null != workCity && ""!=workCity){
//			tri.setWorkCity("%"+workCity.trim()+"%");
			hash.put("workCity", "%"+workCity.trim()+"%");
		}
		if(null != positionDesc && ""!=positionDesc){
//			tri.setPositionDesc("%"+positionDesc.trim()+"%");
			hash.put("positionDesc", "%"+positionDesc.trim()+"%");
		}
		
//		tri.setStatus("on");
		hash.put("status", "on");
		
		try {
			if(null != user){
				List<TbRecruitmentInformation> list = hrService.selectRecruitmentInformationPage(hash, num);
				Integer count = hrService.countRecruitmentInformation(hash);
				mav.addObject("code","0");
				mav.addObject("list",list);
				mav.addObject("count", count);
				mav.addObject("msg","操作成功");
				return mav;
			}else{
				mav.addObject("code","1002");
				mav.addObject("msg","请先登录");
				return mav;
			}
		} catch (Exception e) {
			mav.addObject("code","1003");
			mav.addObject("msg","系统异常，请稍后再试");
			e.printStackTrace();
		}
		return mav;
	}
	
	@RequestMapping(value={"/deliveryInfo"},method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView deliveryInfo(HttpSession session,
			String isRead,
			String isPass
			){
		ModelAndView mav = new ModelAndView();
		TbUser user = (TbUser) session.getAttribute("user");
		TbCandidateRecruitmentInfo cri = new TbCandidateRecruitmentInfo();//求职状态
		if(null!=isPass && ""!=isPass) cri.setIsPass(isPass);
		if(null!=isRead && ""!=isRead) cri.setIsRead(isRead);
		
		try {
			if(null != user){
				cri.setUserId(user.getUserId());
				List<TbRecruitmentInformation> list = userService.selectRecruitmentInformationByCandidate(cri);
				mav.addObject("code","0");
				mav.addObject("list",list);
				return mav;
			}else{
				mav.addObject("code","1002");
				mav.addObject("msg","请先登录");
				return mav;
			}
		} catch (Exception e) {
			mav.addObject("code","1003");
			mav.addObject("msg","系统异常，请稍后再试");
			e.printStackTrace();
		}
		return mav;
	}
	
	@RequestMapping(value={"/application/{id}"},method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView application(HttpSession session,
			@PathVariable("id") String id
			){
		ModelAndView mav = new ModelAndView();
		TbUser user = (TbUser) session.getAttribute("user");
		Calendar calendar = Calendar.getInstance();
		TbCandidateRecruitmentInfo cri = new TbCandidateRecruitmentInfo();
		TbUserResumeRef urr = new TbUserResumeRef();
		
		try {
			if(null != user && null != id && ""!=id){
				cri.setCriId(UUIDFactory.getUUID());
				cri.setDemandTime(calendar.getTime());
				cri.setUserId(user.getUserId());
				cri.setRequirementId(id);
				urr.setUrrId(user.getUserId());
				List<TbResume> list = userService.selectResume(user, new TbResume());
				if(null == list || list.isEmpty()){
					mav.addObject("code","1003");
					mav.addObject("msg","简历为空，请先完善简历");
					return mav;
				}
				cri=commonService.insertCandidateRecruitmentInfo(cri);
				if(null == cri){
					mav.addObject("code","1004");
					mav.addObject("msg","已经投递过简历，请不要重复投递");
				}else{
					mav.addObject("code","0");
					mav.addObject("cri",cri);
					mav.addObject("msg","操作成功");
				}
				return mav;
			}else{
				mav.addObject("code","1002");
				mav.addObject("msg","请先登录");
				return mav;
			}
		} catch (Exception e) {
			mav.addObject("code","1003");
			mav.addObject("msg","系统异常，请稍后再试");
			e.printStackTrace();
		}
		return mav;
	}
	
	@RequestMapping(value={"/projectInfo"},method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView projectInfo(HttpSession session,
			String resumeid,
			String projectName,
			String thePost,
			Integer projectYearStart,
			Integer projectYearEnd,
			Integer projectMonthStart,
			Integer projectMonthEnd,
			String projectDescription
			){
		ModelAndView mav = new ModelAndView();
		TbUser user = (TbUser) session.getAttribute("user");
		TbProjectExperience pe = new TbProjectExperience();
		Calendar calendar = Calendar.getInstance();
		if(null == resumeid || ""==resumeid) {
			mav.addObject("code","1002");
			mav.addObject("msg","请先填写完成基本信息");
			return mav;
		}
		pe.setResumeId(resumeid);
		pe.setrDescribe(projectDescription);
		pe.setName(projectName);
		pe.setDuty(thePost);
		
		if(null  == projectYearStart || projectYearStart <= 0) projectYearStart = 2000;
		if(null  == projectYearEnd || projectYearEnd <=0 ) projectYearEnd = 2000;
		if(null  == projectMonthStart || projectMonthStart < 1 || projectMonthStart > 12) projectMonthStart = 1;
		if(null  == projectMonthEnd || projectMonthEnd < 1 || projectMonthEnd > 12) projectMonthEnd = 1;
		calendar.set(Calendar.YEAR, projectYearStart);
		calendar.set(Calendar.MONTH,projectMonthStart -1);
		pe.setStartTime(calendar.getTime());
		calendar.set(Calendar.YEAR,projectYearEnd);
		calendar.set(Calendar.MONTH,projectMonthEnd-1);
		pe.setEndTime(calendar.getTime());
		
		try {
			if(null != user){
				pe = userService.updateProjectExperience(pe);
				mav.addObject("code","0");
				mav.addObject("pe",pe);
				mav.addObject("msg","操作成功");
				return mav;
			}else{
				mav.addObject("code","1002");
				mav.addObject("msg","请先登录");
				return mav;
			}
		} catch (Exception e) {
			mav.addObject("code","1003");
			mav.addObject("msg","系统异常，请稍后再试");
			e.printStackTrace();
		}
		return mav;
	}
	
	@RequestMapping(value={"/experienceInfo"},method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView experienceInfo(HttpSession session,
			String resumeid,
			String companyName,
			String positionName,
			Integer companyYearStart,
			Integer companyYearEnd,
			Integer companyMonthStart,
			Integer companyMonthEnd 
			){
		ModelAndView mav = new ModelAndView();
		TbUser user = (TbUser) session.getAttribute("user");
		TbResume resume = new TbResume();
		TbWorkExperience we = new TbWorkExperience();
		Calendar calendar = Calendar.getInstance();
		if(null == resumeid || ""==resumeid) {
			mav.addObject("code","1002");
			mav.addObject("msg","请先填写完成基本信息");
			return mav;
		}else{
			resume.setResumeId(resumeid);
		}
		we.setResumeId(resumeid);
		we.setCompany(companyName);
		we.setDuty(positionName);
		if(null  == companyYearStart || companyYearStart <= 0) companyYearStart = 2000;
		if(null  == companyYearEnd || companyYearEnd <=0 ) companyYearEnd = 2000;
		if(null  == companyMonthStart || companyMonthStart < 1 || companyMonthStart > 12) companyMonthStart = 1;
		if(null  == companyMonthEnd || companyMonthEnd < 1 || companyMonthEnd > 12) companyMonthEnd = 1;
		calendar.set(Calendar.YEAR, companyYearStart);
		calendar.set(Calendar.MONTH,companyMonthStart -1);
		we.setStartTime(calendar.getTime());
		calendar.set(Calendar.YEAR,companyYearEnd);
		calendar.set(Calendar.MONTH,companyMonthEnd-1);
		we.setEndTime(calendar.getTime());
		
		try {
			if(null != user){
				we = userService.updateWorkExperience(we);
				mav.addObject("code","0");
				mav.addObject("we",we);
				mav.addObject("msg","操作成功");
				return mav;
			}else{
				mav.addObject("code","1002");
				mav.addObject("msg","请先登录");
				return mav;
			}
		} catch (Exception e) {
			mav.addObject("code","1003");
			mav.addObject("msg","系统异常，请稍后再试");
			e.printStackTrace();
		}
		
		return mav;
	}
	
	@RequestMapping(value={"/expectInfo"},method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView expectInfo(HttpSession session,
			String resumeid,
			String expectCity,
			String expectPosition,
			String expectSalary
			){
		ModelAndView mav = new ModelAndView();
		TbUser user = (TbUser) session.getAttribute("user");
		TbResume resume = new TbResume();
		if(null == resumeid || ""==resumeid) {
			resume.setResumeId(UUIDFactory.getUUID());
		}else{
			resume.setResumeId(resumeid);
		}
		if(null!=expectCity)expectCity=expectCity.replaceAll(",", "");
		if(null!=expectPosition)expectPosition=expectPosition.replaceAll(",", "");
		if(null!=expectSalary)expectSalary=expectSalary.replaceAll(",", "");
		resume.setDesiredLocationDesc(expectCity);
		resume.setDesiredWorkDesc(expectPosition);
		resume.setDesiredSalayDesc(expectSalary);
		
		try {
			if(null != user){
				if(null == resumeid || ""==resumeid){
					resume = userService.addResume(user, resume);
				}else{
					resume = userService.updateResume(user, resume);
				}
				mav.addObject("code","0");
				mav.addObject("resume",resume);
				mav.addObject("msg","操作成功");
				return mav;
			}else{
				mav.addObject("code","1002");
				mav.addObject("msg","请先登录");
				return mav;
			}
		} catch (Exception e) {
			mav.addObject("code","1003");
			mav.addObject("msg","系统异常，请稍后再试");
			e.printStackTrace();
		}
		
		return mav;
	}
	
	@RequestMapping(value={"/basicInfo"},method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView basicInfo(HttpSession session,
			String resumeid,
			String name,
			String topDegree,
			String tel,
			String email,
			String currentState
			){
		ModelAndView mav = new ModelAndView();
		TbUser user = (TbUser) session.getAttribute("user");
		TbResume resume = new TbResume();
		if(null == resumeid || ""==resumeid){
			resume.setResumeId(UUIDFactory.getUUID());
		}else{
			resume.setResumeId(resumeid);
		}
		resume.setName(name);
		resume.setEducationalBackground(topDegree);
		resume.setTelephoneNum(tel);
		resume.setEmail(email);
		resume.setCurrentStatusDesc(currentState);
		
		try {
			if(null != user){
				if(null == resumeid || ""==resumeid){
					resume = userService.addResume(user, resume);
				}else{
					resume = userService.updateResume(user, resume);
				}
				mav.addObject("code","0");
				mav.addObject("resume",resume);
				mav.addObject("msg","操作成功");
				return mav;
			}else{
				mav.addObject("code","1002");
				mav.addObject("msg","请先登录");
				return mav;
			}
		} catch (Exception e) {
			mav.addObject("code","1003");
			mav.addObject("msg","系统异常，请稍后再试");
			e.printStackTrace();
		}
		
		return mav;
	}
	
	@RequestMapping(value={"/getResumeInfoNotId"},method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView getResumeInfoNotId(HttpSession session
			){
		ModelAndView mav = new ModelAndView();
		TbUser user = (TbUser) session.getAttribute("user");
		try {
			if(null != user){
				//获取resume
				//获取resume相关其它信息
				//工作经验
				//项目经验
				//学历
				List<TbResume> list = userService.selectResume(user, new TbResume());
				TbResume resume = null;
				TbWorkExperience we = new TbWorkExperience();
				TbProjectExperience pe = new TbProjectExperience();
				TbSchoolStudyInfo ssi = new TbSchoolStudyInfo();
				if(null != list && !list.isEmpty()){
					resume = list.get(0);
					we.setResumeId(resume.getResumeId());
					pe.setResumeId(resume.getResumeId());
					ssi.setResumeId(resume.getResumeId());
					
					we = userService.selectWorkExperience(we);
					pe = userService.selectProjectExperience(pe);
					ssi = userService.selectSchoolStudyInfo(ssi);
					
					mav.addObject("resume",resume);
					mav.addObject("we",we);
					mav.addObject("pe",pe);
					mav.addObject("ssi",ssi);
				}else{
					mav.addObject("code","1001");
					mav.addObject("msg","简历为空");
					return mav;
				}
				mav.addObject("code","0");
				mav.addObject("msg","操作成功");
				return mav;
			}else{
				mav.addObject("code","1002");
				mav.addObject("msg","请先登录");
				return mav;
			}
		} catch (Exception e) {
			mav.addObject("code","1003");
			mav.addObject("msg","系统异常，请稍后再试");
			e.printStackTrace();
		}
		return mav;
	}
	
	
	@RequestMapping(value="/getRecruitmentInformations",method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView getRecruitmentInformations(HttpSession session,
			String salaryMin,
			String edu,
			String workCity,
			String positionDesc
			){
		ModelAndView mav = new ModelAndView();
		TbUser user = (TbUser) session.getAttribute("user");
		TbRecruitmentInformation tri = new TbRecruitmentInformation();
		if(null != salaryMin && ""!=salaryMin)	tri.setSalaryMin(salaryMin.trim());
		if(null != edu && ""!=edu)	tri.setEducationalBackgroundDesc("%"+edu.trim()+"%");
		if(null != workCity && ""!=workCity)	tri.setWorkCity("%"+workCity.trim()+"%");
		if(null != positionDesc && ""!=positionDesc)	tri.setPositionDesc("%"+positionDesc.trim()+"%");
		
		tri.setStatus("on");
		
		try {
			if(null != user){
				List<TbRecruitmentInformation> list = hrService.selectRecruitmentInformation(tri);
				mav.addObject("code","0");
				mav.addObject("list",list);
				mav.addObject("msg","操作成功");
				return mav;
			}else{
				mav.addObject("code","1002");
				mav.addObject("msg","请先登录");
				return mav;
			}
		} catch (Exception e) {
			mav.addObject("code","1003");
			mav.addObject("msg","系统异常，请稍后再试");
			e.printStackTrace();
		}
		return mav;
	}
	
	@RequestMapping(value="/updateUserPwd",method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView register(HttpSession session,
			String oldpassword,
			String newpassword){
		ModelAndView mav = new ModelAndView();
		TbUser user = (TbUser) session.getAttribute("user");
		
		try {
			if(null != user){
				if(oldpassword.equals(user.getUserPassword())){
					user.setUserPassword(newpassword);
					user = userService.updateUser(user);
					if( null != user){
						mav.addObject("code","0");
						mav.addObject("msg","更新成功");
						mav.addObject("href","common/login");
						return mav;
					}else{
						mav.addObject("code","1003");
						mav.addObject("msg","更新失败，请稍后再试");
						return mav;
					}
				}else{
					mav.addObject("code","1004");
					mav.addObject("msg","旧密码错误，请重新输入");
					return mav;
				}
			}else{
				mav.addObject("code","1002");
				mav.addObject("msg","请先登录");
				return mav;
			}
		} catch (Exception e) {
			e.printStackTrace();
			mav.addObject("code","1001");
			mav.addObject("msg","系统异常，请稍后再试");
		}
		return mav;
	}
			
			
	@RequestMapping(value="/register",method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView register(
			HttpSession session, String type,String name, String email, String password){
		ModelAndView mav = new ModelAndView();
		TbUser user = new TbUser();
		user.setUserCreateTime(Calendar.getInstance().getTime());
		user.setUserEmail(email);
		user.setUserId(UUIDFactory.getUUID());
		user.setUserIdentity(type);
		user.setUserPassword(password);
		user.setUserStatus("0");
		try {
			if(null == userService.register(user)){
				mav.addObject("code","1001");
				mav.addObject("msg","邮箱已被注册，请重新注册邮箱");
			}else{
				mav.addObject("code","0");
				mav.addObject("msg","注册成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			mav.addObject("code","1001");
			mav.addObject("msg","注册失败，请稍后再试");
		}
		return mav;
	}
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView login(
			HttpSession session,
			String email, String password){
		ModelAndView mav = new ModelAndView();
		TbUser user = new TbUser();
		user.setUserEmail(email);
		user.setUserPassword(password);
		try {
			user = userService.selectUser(user);
			if(null != user){
				session.setAttribute("user", user);
				mav.addObject("code","0");
				mav.addObject("msg","登录成功");
			}else{
				mav.addObject("code","1001");
				mav.addObject("msg","用户不存在或密码出错");
			}
		//用户用为hr与user2种，他们进入的页面是不同的。
			// hr 进入的页面，也是不同的
			if(null != user){
				if("1".equals(user.getUserIdentity())){
					TbHr hr = new TbHr();
					hr.setUserId(user.getUserId());
					hr = hrService.selectHrByUserId(hr);
					if(null == hr){
						//公司还没有创建
						mav.addObject("href","common/createCompany01");
					}else{
						//公司已经创建
						mav.addObject("href","hr/myhome");
					}
				}else{
					//求职者页面
					mav.addObject("href","user/resume/delivery");
				}
			}
			
		} catch (Exception e) {
			mav.addObject("code","1001");
			mav.addObject("msg","系统出错，请稍后再试");
			e.printStackTrace();
		}
		return mav;
	}
	
	@RequestMapping("/updatepsw")
	public String updatepsw(HttpServletRequest request, Model model){
		System.out.println("validate fo update personal password page");
		return "user/personal/updatePwd";
	}
	
	@RequestMapping("/resume/delivery")
	public String resumeDelivery(HttpServletRequest request, Model model){
		System.out.println("validate fo update personal password page");
		return "user/resume/delivery";
	}
	
	@RequestMapping("/resume/jianli")
	public String resumeJianli(HttpServletRequest request, Model model){
		System.out.println("validate fo user resume jianli page");
		return "user/resume/jianli";
	}
	
	@RequestMapping("/position/list")
	public String positionList(HttpServletRequest request, Model model){
		System.out.println("validate fo user position list page");
		return "user/position/list";
	}
	
	@RequestMapping("/jobDetail/{id}")
	public String positionList(HttpServletRequest request, Model model,
			@PathVariable("id") String id) throws Exception{
		System.out.println("validate fo user job detail page and id = " + id);
		request.setAttribute("id", id);
		TbRecruitmentInformation tri = new TbRecruitmentInformation();
		tri.setRiId(id);
		List<TbRecruitmentInformation> list = hrService.selectRecruitmentInformation(tri);
		if(null != list && !list.isEmpty()){
			request.setAttribute("tri",list.get(0));
			TbCompany company = new TbCompany();
			company.setCompanyId(list.get(0).getCompanyId());
			company = hrService.selectCompanyById(company);
			request.setAttribute("company",company);
		}
		
		return "user/company/jobdetail";
	}
	
	@RequestMapping(value={"/getResumeInfo/{id}"},method=RequestMethod.GET)
	public String getResumeInfoByUserId(HttpSession session,HttpServletRequest request,
			@PathVariable("id") String id){
		System.out.println("validate to user preview page...");
		TbUser user = new TbUser();
		try {
			if(null == id || ""==id){
				request.setAttribute("code","1001");
				request.setAttribute("msg","无法获取数据");
			}else{
				user.setUserId(id);
				//获取resume
				//获取resume相关其它信息
				//工作经验
				//项目经验
				//学历
				List<TbResume> list = userService.selectResume(user, new TbResume());
				TbResume resume = null;
				TbWorkExperience we = new TbWorkExperience();
				TbProjectExperience pe = new TbProjectExperience();
				TbSchoolStudyInfo ssi = new TbSchoolStudyInfo();
				if(null != list && !list.isEmpty()){
					resume = list.get(0);
					we.setResumeId(resume.getResumeId());
					pe.setResumeId(resume.getResumeId());
					ssi.setResumeId(resume.getResumeId());
					
					we = userService.selectWorkExperience(we);
					pe = userService.selectProjectExperience(pe);
					ssi = userService.selectSchoolStudyInfo(ssi);
					
					request.setAttribute("resume",resume);
					request.setAttribute("we",we);
					request.setAttribute("pe",pe);
					request.setAttribute("ssi",ssi);
					
					request.setAttribute("code","0");
					request.setAttribute("msg","操作成功");
				}else{
					request.setAttribute("code","1002");
					request.setAttribute("msg","简历为空");
				}
				
			}
			
		} catch (Exception e) {
			request.setAttribute("code","1004");
			request.setAttribute("msg","系统异常，请稍后再试");
			e.printStackTrace();
		}
		return "user/resume/preview";
	}
	
}
